<template>
  <nut-input v-model="outputText" placeholder="请选择商户或门店" readonly :disabled="props.disabled" @click-input="clickInput"
    :input-align="props.inputAlign" :input-class="{ 'ipt-sl': isSL }">
    <template #right v-if="!hiddenSelf && type === 'M'">
      <nut-switch v-model="self" size="mini" active-value="1" inactive-value="0" active-text="仅商户" inactive-text="所有" />
    </template>
  </nut-input>
  <nut-cascader v-model:visible="visible" v-model="innerValue" title="商户门店选择" :options="options"
    @path-change="pathChange" />
</template>

<script lang="ts" setup>
import mcht from '@/api/mcht'

import { useHomeStore } from '@/store'
const { mchtNo } = storeToRefs(useHomeStore())

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  hiddenSelf: {
    type: Boolean,
    default: false
  },
  inputAlign: {
    type: String,
    default: 'left',
  },
  isScreening: {
    type: Boolean,
    default: false
  },
  isSL: {
    type: Boolean,
    default: true,
  },
})

const model = defineModel({ type: String })
const type = defineModel('type', { type: String })
const self = defineModel('self', { type: String })
const outputText = defineModel('outputText', { type: String })
const visible = ref(false)
// const outputText = ref('')
const innerValue = ref<string[]>([])
function clickInput() {
  if (!props.disabled) {
    visible.value = true
  }
}

const emits = defineEmits(['pathChange'])
const pathChange = (pathNodes: any) => {
  if (pathNodes[1]) {
    model.value = pathNodes[1].value
    outputText.value = pathNodes[1].text
    type.value = 'S'
  } else {
    model.value = pathNodes[0].value
    outputText.value = pathNodes[0].text
    type.value = 'M'
  }
  emits('pathChange', pathNodes)
}
const options = ref([])

onMounted(async () => {
  const { data } = await mcht.getMchtStoreList()
  if (data.status === 'success') {
    options.value = data.data.mchtList.map((mcht: any) => {
      if (mcht.mchtNo === model.value) {
        outputText.value = mcht.mchtNm
        innerValue.value.push(mcht.mchtNo)
        type.value = 'M'
      }
      return {
        text: mcht.mchtNm,
        value: mcht.mchtNo,
        children: mcht.shops.map((shop: any) => {
          if (shop.shopId === model.value) {
            outputText.value = shop.shopNm
            innerValue.value.push(mcht.mchtNo)
            innerValue.value.push(shop.shopId)
            type.value = 'S'
          }
          return {
            text: shop.shopNm,
            value: shop.shopId
          }
        })
      }
    })
    console.log(options.value)
    console.log(mchtNo.value)
    if (props.isScreening){
      let list = options.value
      options.value = list.filter(item => item.value === mchtNo.value);
    }
    // outputText.value = '这里是名称很长的文本名字展示看看效果是否有截取'
  }
})
</script>

